import objectUtils from "@/utils/object/index.js";
import config from '@/config/index.js';

export default objectUtils.freeze({
	fullPath: function(name){
		if(name){
			if(name.startsWith("http://") || name.startsWith("https://")){
				return name;
			}else{
				return config.imgURL + name;
			}
		}else{
			return "";
		}
	},
	
	// 获取文件信息的辅助函数
	getFileInfo: function(filePath) {
		return new Promise((resolve, reject) => {
			uni.getFileInfo({
				filePath,
				success: (res) => resolve(res),
				fail: (err) => reject(err)
			});
		});
	},

	/**
	* 选择并上传图片
	* @param options 配置选项
	* @returns 成功上传的图片URL数组
	*/
	uploadImages: function(options) {
    const { countResidueFn, sizeLimit, modelValue, page, upload, sourceType } = options;

    return new Promise((resolve) => {
			uni.chooseImage({
				count: countResidueFn(),
				sourceType: sourceType,
				success: async (res) => {
					if (res.errMsg !== "chooseImage:ok") {
						resolve([]);
						return;
					}
					uni.showLoading({
						title: '上传中',
						mask: true
					});

					const MAX_SIZE = sizeLimit * 1024 * 1024;
					const uploadedUrls = [];
					const tempFilePaths = res.tempFilePaths;

					// 检查文件大小
					for (const filePath of tempFilePaths) {
						try {
							const fileInfo = await this.getFileInfo(filePath);
							if (fileInfo.size > MAX_SIZE) {
								uni.hideLoading();
								uni.showToast({
									title: `文件超过${sizeLimit}MB限制`,
									icon: 'none',
									duration: 3000
								});
								resolve([]);
								return; // 停止后续操作
							}
						} catch (error) {
							uni.hideLoading();
							console.error('获取文件信息失败:', error);
							resolve([]);
							return; // 停止后续操作
						}
					}

					// 批量上传
					const totalFiles = tempFilePaths.length;

					for (let i = 0; i < tempFilePaths.length; i++) {
						const filePath = tempFilePaths[i];
						try {
							const progressCallback = (progress) => {
								const current = i + 1;
								if (progress < 100) {
									page?.loading.show(`上传中 (${current}/${totalFiles}): ${progress}%`);
								} else {
									page?.loading.show(`保存中 (${current}/${totalFiles})`);
								}
							};

							const result = await upload(filePath, progressCallback);
							uploadedUrls.push(result);
							uni.hideLoading();
						} catch (error) {
							uni.hideLoading();
							console.error('文件上传失败:', error);
							resolve([]);
							return; // 停止后续操作
						}
					}

					// 如果所有文件都上传成功，返回结果
					resolve(uploadedUrls); // 这里可以根据实际需求调整返回值
				},
				fail: () => {
					uni.hideLoading();
					resolve([]);
				}
			});
    });
}
});
